package cn.edu.gsau.info.models;

import com.alibaba.fastjson.annotation.JSONField;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

@Data
@NoArgsConstructor
//@AllArgsConstructor
public class LoginUser implements UserDetails {
    private User user;

    //1:用List集合存储用户的权限
    private List<String> permissions;

    public LoginUser(User user, List<String> permissions) {
        this.user = user;
        this.permissions = permissions;
    }

    //2:实现getAuthorities方法，将permissions中的权限转换为getAuthorities方法返回值类型的权限
    @Override
    //3：法返回的角色不进行JSON转换，我们使用permissions中存储的角色进行json转换
    @JSONField(serialize = false)
    public Collection<? extends GrantedAuthority> getAuthorities() {
        List<GrantedAuthority> roles = new ArrayList<>();
        if(permissions!=null && permissions.size()>0){
            for (int i = 0; i < permissions.size(); i++) {
                SimpleGrantedAuthority authority = new SimpleGrantedAuthority(permissions.get(i));
                roles.add(authority);

            }

        }
        return roles;
    }

    @Override
    public String getPassword() {
        return user.getPassword();
    }

    @Override
    public String getUsername() {
        return user.getUserName();
    }

    @Override
    public boolean isAccountNonExpired() {
        return true;
    }

    @Override
    public boolean isAccountNonLocked() {
        return true;
    }

    @Override
    public boolean isCredentialsNonExpired() {
        return true;
    }

    @Override
    public boolean isEnabled() {
        return true;
    }

    public void setUser(User user) {
        this.user = user;
    }

    public void setPermissions(List<String> permissions) {
        this.permissions = permissions;
    }

    public User getUser() {
        return user;
    }
    public String getNickName(){return user.getNickName();}

    public List<String> getPermissions() {
        return permissions;
    }



}
